package hjw.com.controller.adm;

import hjw.com.dao.ClzMapper;
import hjw.com.entity.Clz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/adm/clz")
@SuppressWarnings("all")
public class AdmClzController {
    @Autowired
    ClzMapper clzMapper;

    @GetMapping("/go2Add/{curPage}")
    public String go2Add(@PathVariable ("curPage")Integer curPage){
        return "forward:/adm/clz/prevPage?curPage=" + curPage;
    }

    @RequestMapping({"/prevPage","/nextPage"})
    public String prevPage(Integer curPage, Model model){
        final int pageSize = 6;//设置固定的每页显示数量
        Integer start = 1;
        if (curPage == null) curPage = 1;//初始化页数
        Integer count = clzMapper.count();//数据库含有的数据的总行数
        Integer totalPage = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;//计算出最大页数
        System.out.println(totalPage +"--" + curPage);
        if (curPage > totalPage) curPage = totalPage;//限制显示页数不能大于总行数
        if (curPage != null) start = curPage;//获取每页提交过来的页码并赋值
        List<Clz> clzs = clzMapper.findByLine((start-1) * pageSize, pageSize);
        model.addAttribute("curPage",start);//设置当前页数
        model.addAttribute("totalPage",totalPage);//设置计算出最大页数
        model.addAttribute("clzs",clzs );//设置当前页内容
        model.addAttribute("clz",new Clz());
        model.addAttribute("action","doAdd");
        return "adm/clz/All";
    }

    @RequestMapping("/go2update")
    public String goUpdate(String clzno,Integer curPage,Model model){
        this.prevPage(curPage,model);//初始化分页页面显示
        Clz clz = clzMapper.findByClzno(clzno);//根据Id查找数据库对应的clz
        model.addAttribute("cou",clz);
        model.addAttribute("action","update");
        return "adm/clz/All";
    }

    @PostMapping("/update")
    public String update(Clz clz,Integer curPage,Model model){
        int update = clzMapper.updateById(clz);
        model.addAttribute("state",update > 0 ? "修改成功":"修改失败");
        return "forward:/adm/clz/prevPage?curPage=" + curPage;
    }

    @PostMapping("/doAdd")
    public String doAdd(Clz clz,Integer curPage,Model model){
        int add = clzMapper.add(clz);
        model.addAttribute("state",add > 0 ? "添加成功":"添加失败");
        return "forward:/adm/clz/prevPage?curPage=" + curPage;
    }

    @GetMapping("/delete")
    public String removeById(String clzno,Integer curPage,Model model){
        int i = clzMapper.removeById(clzno);
        model.addAttribute("state",i > 0 ? "删除成功":"删除失败");
        return "forward:/adm/clz/prevPage?curPage=" + curPage;
    }

}
